/* author: jiamn, jia_mn@qq.com, 2021.8.13  */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

//#define DBG
//#define MAX_KEY_NUM 256
#define MAX_LINE_LENGTH 512
#define MAX_KEY_LENGTH 256

char *del_left_trim(char *str)
{
    if (str == NULL || *str == '\0'){
        return str;
    }
    int len = 0;
    char *p = str;
    while (*p != '\0' && isspace(*p)){
        ++p;
        ++len;
    }
    memmove(str, p, strlen(str) - len + 1);
    return str;
}

char *del_both_trim(char *str)
{
    char *p, *sOut;
    del_left_trim(str);
    sOut = str;
    for (p = sOut + strlen(sOut) - 1; p >= sOut && isblank(*p); --p);
    *(++p) = '\0';
    return sOut;
}

int GetKeyValue(char *title, char *key, char *value, FILE *fp)
//Get value of key in seg [title] of file (fp)
//fp is open
// 0: both none;
// 101: seg[title] once and  key once in this seg;   ((seg times) * 100 + (key times))
// 100: seg[title] once and nokey in this seg;
{
        int  ret = 0;
        char segTitle[MAX_KEY_LENGTH];
        char sget[MAX_KEY_LENGTH];
        char *delim = "=";
        char *pget;
        char chget;

        sprintf(segTitle, "[%s]", title);
    fseek(fp, 0L, SEEK_SET);

    while (1)
        {
            pget = fgets(sget, MAX_LINE_LENGTH, fp);
            if (feof(fp)) break;
            if (strlen(sget) == 1) continue;
            if (pget != NULL){
                del_both_trim(sget);
//                strcpy(sget, pget);
                chget = sget[0];
                if (chget == '#' || isblank(chget) || chget == '\n') continue;
                if (chget == '['){
                    if (strncmp(segTitle, sget, strlen(segTitle)) == 0){
        #ifdef DBG
                        printf("Func: found %s\n", sget);
        #endif
                        ret = 100;
                        continue;
                    }else{   //not this title but is another title
                        if (ret == 100){
        #ifdef DBG
                            printf("Just find Title %s but cant find key %s in this seg.\n", title, key);
        #endif
                            return ret;
                        }else{
                            continue;
                        }
                    }
                }else{   //not seg title line
                    pget = strtok(sget, delim);
                    del_both_trim(pget);
                            if ((strcmp(pget, key) == 0) && (100 == ret)){
                        pget = strtok(NULL, delim);
                        pget[strlen(pget)-1] = 0;
                        del_both_trim(pget);
                        strcpy(value, pget);
        #ifdef DBG
                        printf("Found value: %s.\n", value);
        #endif
                        return 101;
                            }
                }
            } //if pfgets !=NULL
        }

    return ret;
}